package org.alicuu.mvc.servlet;

import org.alicuu.Kumamon;
import org.alicuu.mvc.render.Render;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by IntelliJ IDEA.
 * User: Danny
 * Date: 16/07/06
 * Time: 09:32
 */
public class Response {
    private HttpServletResponse rawResponse;
    private Render render = null;

    public Response(HttpServletResponse rawResponse) {
        this.rawResponse = rawResponse;
        this.rawResponse.setHeader("Framework", "Kumamon");
        this.render = Kumamon.getInstance().getRender();
    }

    public void text(String text) {
        rawResponse.setContentType("text/plan;charset=UTF-8");
        this.print(text);
    }

    public void html(String html) {
        rawResponse.setContentType("text/html;charset=UTF-8");
        this.print(html);
    }

    private void print(String str) {
        try {
            OutputStream outputStream = rawResponse.getOutputStream();
            outputStream.write(str.getBytes());
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void cookie(String name, String value) {
        Cookie cookie = new Cookie(name, value);
        rawResponse.addCookie(cookie);
    }

    public HttpServletResponse getRawResponse() {
        return rawResponse;
    }

    public void render(String view) {
        render.render(view, null);
    }

    public void redirect(String location) {
        try {
            rawResponse.sendRedirect(location);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
